package com.heaboy.feedback.websocket;


import com.fasterxml.jackson.databind.ObjectMapper;
import com.heaboy.feedback.websocket.domain.Message;
import com.heaboy.feedback.websocket.handler.MessageHandler;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.*;
import io.netty.channel.group.ChannelGroup;
import io.netty.channel.group.ChannelGroupFuture;
import io.netty.channel.group.DefaultChannelGroup;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import io.netty.util.AttributeKey;
import io.netty.util.CharsetUtil;
import io.netty.util.concurrent.GlobalEventExecutor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;


@Slf4j
@Component
@ChannelHandler.Sharable
public class WsWebSocketHandler extends SimpleChannelInboundHandler<TextWebSocketFrame> {

    @Autowired
    private WsContineHandler wsContineHandler;

    @Autowired
    @Qualifier("teacherMessageHandler")
    private MessageHandler teacherMessageHandler;
    @Autowired
    @Qualifier("studentMessageHandler")
    private MessageHandler studentMessageHandler;
    // 课号 -》 学生chanelgroup
    private ConcurrentHashMap<String, ChannelGroup> studentChannelGroups = new ConcurrentHashMap<String, ChannelGroup>();
    // 课号-》 教师group
    private ConcurrentHashMap<String, ChannelGroup> teacherChannelGroups = new ConcurrentHashMap<>();

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        log.info("有人连接进来了");
        super.channelActive(ctx);
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
        // 记录日志
        cause.printStackTrace();
        ctx.close();
    }


    @Override
    public void channelInactive(ChannelHandlerContext ctx) {

        log.info("有人退出");
    }


    @Override
    protected void channelRead0(ChannelHandlerContext ctx, TextWebSocketFrame msg) throws Exception {
        //正常的TEXT消息类型

        ObjectMapper mapper = new ObjectMapper();
        log.info(msg.text());
        Message message = mapper.readValue(msg.text(), Message.class);
        Long lessonId = message.getLessonId();
        if (wsContineHandler.isTeacherChannel(ctx.channel())) {
            log.info("教师方向");
            ChannelGroup teacherGroup = teacherChannelGroups.getOrDefault(lessonId.toString(), new DefaultChannelGroup(GlobalEventExecutor.INSTANCE));
            teacherGroup.add(ctx.channel());
            teacherChannelGroups.put(lessonId.toString(), teacherGroup);
            teacherMessageHandler.handle(message);

        } else {
            ChannelGroup studentGroup = studentChannelGroups.getOrDefault(lessonId.toString(), new DefaultChannelGroup(GlobalEventExecutor.INSTANCE));
            studentGroup.add(ctx.channel());
            log.info("学生方向");
            studentChannelGroups.put(lessonId.toString(), studentGroup);

            studentMessageHandler.handle(message);
        }
    }

    public void sendToTeacher(String key, String msg) {
        log.info("向老师发送消息" + key + "--" + msg);
//        ByteBuf byteBuf = Unpooled.copiedBuffer(msg, CharsetUtil.UTF_8);
        ChannelGroup channels = teacherChannelGroups.get(key);
        if (channels != null) {
            channels.writeAndFlush(new TextWebSocketFrame(msg));
        } else {
            log.error(key + "没有老师");
        }

    }

    public void sendToStudent(String key, String msg) {
        log.info("向学生发送消息" + key + "--" + msg);
         ChannelGroup channels = studentChannelGroups.get(key);
        if (channels != null) {
             channels.writeAndFlush(new TextWebSocketFrame(msg));
        } else {
            log.error(key + "没有学生");
        }

    }


}
